import time

from zz import zz_code, zz_dingtalk, zz_return, zz_log, zz_str
import requests

log = zz_log.of()


def config_to_arr() -> list:
    """
    配置 转 r
    :return:
    """
    fund_config_str = zz_code.get_file_content("./fund.json")
    return zz_return.parse_arr(fund_config_str)


def run():
    # 基金代码；买入净值
    # token = zz_code.env("FUND_TOKEN")
    # token_arr = zz_str.split2(token)
    # log.info(token_arr)
    # if token_arr is None:
    #     log.error('未配置FUND_TOKEN')
    #     return
    config_arr = config_to_arr()
    if config_arr is None:
        log.error('未配置FUND_TOKEN')
        return

    buy_count = 0  # 需要买入数量
    log_msg = f'**基基基** [{zz_code.date_tostring()}]\n\n'
    for item in config_arr:
        handle = Handle(item)

        r = handle.run_one()
        time.sleep(1)
        if r.get_errcode() == 888:
            buy_count = buy_count + 1

        log.info(r.get_errmsg())
        log_msg += r.get_errmsg() + "\n\n"

    title = "基基基"
    if buy_count > 0:
        title = f"基操作：{buy_count}/{len(config_arr)}"

    zz_dingtalk.send_markdown(log_msg, title)


# 蒙自源
class Handle:
    def __init__(self, r: zz_return.Return):
        self.fund_code = r.get_data("fund_code")  # 基金编号
        self.buy_net = float(r.get_data("buy_net"))  # 买入净值

        self.sell_enable = r.get_data("sell_enable")  # 开启买出
        if self.sell_enable is None:
            self.sell_enable = 0

        self.sell_net = float(r.get_data("sell_net"))  # 买出净值
        if self.sell_net is None:
            self.sell_net = float(0)

    def run_one(self) -> zz_return.Return:
        if zz_str.is_null_or_empty(self.fund_code):
            return zz_return.of(20037, "缺少基金参数")
        #
        log_msg = ''
        r = self.get_fund_info()
        fund_name = r.get_data("name")
        fund_code = r.get_data("fundcode")
        fund_net = float(r.get_data("gsz"))  # 实时净值
        fund_net_rate = r.get_data("gszzl")  # 升降百分比
        # 下次买入净值
        next_buy_net = round(self.buy_net * (1 - 0.04), 4)
        #
        r = zz_return.of(0)
        #
        action_msg = ""
        fund_msg = ""
        if self.sell_enable == 1:  # 开启买出
            next_sell_net = round(self.sell_net * (1 + 0.04), 4)
            if fund_net >= next_sell_net:
                r.set_errcode(888)
                action_msg = "操作：**买出买出买出**"
                fund_code = f"**{fund_code}**"
                next_sell_net = f"**{next_sell_net}**"
            else:
                next_sell_net_rate = round((next_sell_net - fund_net) / fund_net * 100, 2)  # 相差百分比
                next_sell_net = f"{next_sell_net} [差↑{next_sell_net_rate}%]"
            fund_msg += f"★买出时机(4%)：{next_sell_net}\n\n"
        else:  # 买入
            if fund_net <= next_buy_net:
                r.set_errcode(888)
                action_msg = "操作：**买入买入买入**"
                next_buy_net = f"**{next_buy_net}**"
                fund_code = f"**{fund_code}**"
            else:
                next_buy_net_rate = round((fund_net - next_buy_net) / next_buy_net * 100, 2)  # 相差百分比
                next_buy_net = f"{next_buy_net} [差↓{next_buy_net_rate}%]"
            fund_msg += f"买入时机(4%)：{next_buy_net}\n\n"

        fund_msg += f"{action_msg}\n\n--"
        log_msg = f"[{fund_code}]{fund_name}\n\n实时净值：**{fund_net}**[{fund_net_rate}%]\n\n" + fund_msg

        r.set_errmsg(log_msg)
        return r

    """
    基金信息
    name：名称
    fundcode：基金代码
    gztime：更新时间
    gsz：最新净值
    gszzl：升降百分比
     {'fundcode': '008929', 'name': '宏利消费红利指数C', 'jzrq': '2025-04-29', 'dwjz': '1.5122', 'gsz': '1.4953', 'gszzl': '-1.12', 'gztime': '2025-04-30 15:00'}
    """

    def get_fund_info(self) -> zz_return.Return:
        api_url = f"https://fundgz.1234567.com.cn/js/{self.fund_code}.js?rt=1746241232544"
        html = self.get_html(api_url)
        fund_data_str = html.replace("jsonpgz(", "")
        fund_data_str = fund_data_str.replace(");", "")
        return zz_return.parse(fund_data_str)

    def get_headers(self):
        headers = {
        }
        user_agent = zz_code.env("USER_AGENT")
        if zz_str.has_any_text(user_agent):
            headers['User-Agent'] = user_agent

        return headers

    def get_html(self, api_url):
        headers = self.get_headers()

        log.debug(api_url)
        log.debug(headers)
        res = requests.get(api_url, headers=headers)
        if res.content is None or res.status_code != 200:
            return ''
        return res.content.decode('utf-8')


if __name__ == '__main__':
    run()
